package com.sea.operate.controller;


import com.codecrane.core.power.service.PowerUserService;
import com.codecrane.core.util.DateUtils;
import com.codecrane.core.util.ExcelUtil;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.codecrane.core.web.AjaxTableReturn;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.sea.operate.entity.Related;
import com.sea.operate.entity.RelatedSku;
import com.sea.operate.service.RelatedSkuService;
import com.sea.product.service.ChannelService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


/**
 *  控制器
 * @author 陈鸿飞
 *  <br/>
 *  <br/>
 */
@Controller
@RequestMapping("/sea/operate/relatedSku")
public class RelatedSkuController {

    @Autowired
    private ChannelService channelService;
    @Autowired
    private RelatedSkuService relatedSkuService;
    @Autowired
    private PowerUserService powerUserService;

    public static void main(String[] args) {
        String pdfUrl = "http://cozylux-related.oss-cn-beijing.aliyuncs.com/CLUS24G20U7QU.pdf?Expires=3312347898&OSSAccessKeyId=LTAI4G55LJEk8nARtrjYngou&Signature=7o3NettqUCh%2BeDqRM7OMs%2B70FRw%3D";

        try (InputStream inputStream = new URL(pdfUrl).openStream();
             PDDocument document = PDDocument.load(inputStream)) {

            PDFRenderer pdfRenderer = new PDFRenderer(document);

            for (int page = 0; page < document.getNumberOfPages(); page++) {
                // 将PDF页面渲染为图像
                BufferedImage image = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB);

                // 调用ZXing库来解码条形码
                Result result = decodeBarcode(image);
                if (result != null) {
                    System.out.println("Page " + (page + 1) + ": " + result.getText());
                } else {
                    System.out.println("Page " + (page + 1) + ": No barcode found.");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Result decodeBarcode(BufferedImage image) {
        try {
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

            HashMap<DecodeHintType, Object> hints = new HashMap<>();
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);

            MultiFormatReader reader = new MultiFormatReader();
            return reader.decode(bitmap, hints);
        } catch (NotFoundException e) {
            // 未找到条形码
            return null;
        }
    }

    /**
     * 管理主页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/main")
    public String main(Model model) {
        model.addAttribute("channel", channelService.findByCnd(null));
        return "/sea/operate/relatedSku/main";
    }

    @RequestMapping("/addSku")
    public String addSku(Model model) {
        model.addAttribute("channel", channelService.findByCnd(null));
        model.addAttribute("operate", powerUserService.findByGroupId(22));
        return "/sea/operate/relatedSku/addSku";
    }

    @RequestMapping("/editSku")
    public String addSku(Model model, @RequestParam("id") Integer id) {
        model.addAttribute("channel", channelService.findByCnd(null));
        model.addAttribute("operate", powerUserService.findByGroupId(22));
        model.addAttribute("relatedSku", relatedSkuService.findById(id));
        return "/sea/operate/relatedSku/editSku";
    }

    /**
     * 分页条件查询
     *
     * @param relatedSku
     * @return
     */
    @ResponseBody
    @RequestMapping("/findByCnd")
    public AjaxTableReturn findByCnd(@RequestParam(value = "limit", defaultValue = "10") int pagesize,
                                     @RequestParam(value = "offset", defaultValue = "0") int start,
                                     RelatedSku relatedSku) {
        start = start > 0 ? start / pagesize + 1 : 1;
        PageHelper.startPage(start, pagesize);
        List<RelatedSku> relatedList = relatedSkuService.findByCnd(relatedSku);
        PageInfo<RelatedSku> page = new PageInfo<>(relatedList);
        return Ajax.tableDataOk(page.getTotal(), page.getList());
    }

    /**
     * 修改
     *
     * @param relatedSku
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public AjaxReturn save(RelatedSku relatedSku) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null != relatedSku && relatedSkuService.save(relatedSku) > 0) {
                relatedSkuService.updateListingName();
                result.setOk(true).setMsg("保存成功！");
            }
        } catch (RuntimeException e) {
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 修改
     *
     * @param relatedSku
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/findByChannelSku", method = RequestMethod.POST)
    public AjaxReturn findByChannelSku(RelatedSku relatedSku) {
        AjaxReturn result = Ajax.fail().setMsg("查询失败！");
        try {
            RelatedSku related = relatedSkuService.findByChannelSku(relatedSku);
            if (null != related) {
                result.setOk(true).setData(related);
                result.setOk(true).setMsg("查询成功！");
            }
        } catch (RuntimeException e) {
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }

    /**
     * 修改
     *
     * @param relatedSku
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/usave", method = RequestMethod.POST)
    public AjaxReturn usave(RelatedSku relatedSku) {
        AjaxReturn result = Ajax.fail().setMsg("修改失败！");
        try {
            if (null != relatedSku && relatedSkuService.usave(relatedSku) > 0) {
                relatedSkuService.updateListingName();
                result.setOk(true).setMsg("修改成功！");
            }
        } catch (RuntimeException e) {
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("系统异常,请联系管理员!");
            return result;
        }
        return result;
    }


    @RequestMapping("/import")
    @ResponseBody
    public AjaxReturn importSku(Model model, MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".xls"))) {
                    return result.setMsg("只能上传excel文件！！！");
                }
                relatedSkuService.importRelated(file.getInputStream(), fileName);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        }
        return result;
    }

    @RequestMapping("/importFlag")
    @ResponseBody
    public AjaxReturn importFlag(Model model, MultipartFile file) {
        AjaxReturn result = Ajax.fail().setMsg("保存失败！");
        try {
            if (null == file || file.isEmpty()) {
                return result.setMsg("请上传文件！！！");
            } else {
                String fileName = file.getOriginalFilename();
                if (!(fileName.contains(".zip"))) {
                    return result.setMsg("只能上传zip文件！！！");
                }

                relatedSkuService.importRelatedFlag(file, fileName);
                result.setOk(true);
                result.setMsg("上传成功！！");
            }
        }catch (RuntimeException e) {
            e.printStackTrace();
            result.setMsg(e.getMessage());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setMsg("系统异常，请联系管理员");
            return result;
        }
        return result;
    }





    private File Mfile(MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        File file = new File(fileName);
        OutputStream out = null;
        try {
            //获取文件流，以文件流的方式输出到新文件
//    InputStream in = multipartFile.getInputStream();
            out = new FileOutputStream(file);
            byte[] ss = multipartFile.getBytes();
            for (int i = 0; i < ss.length; i++) {
                out.write(ss[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return  file;
    }

    /**
     * 导出收货数据
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response, RelatedSku relatedSku) {
        List<RelatedSku> list=relatedSkuService.findByCnd(relatedSku);
        String[] title = {"Listing名称","Listing名称(EN)","渠道","SKU","产品名称","产品名称(EN)","产品颜色","产品属性","尺码","FNSKU","ASIN","运营人员","产品标"};
        String fileName = "对照表" + DateUtils.dateToString(new Date(),"yyyyMMdd") + ".xls";
        String sheetName = "对照表";
        String[][] content = new String[list.size()][13];
        for (int i = 0; i < list.size(); i++) {
            content[i] = new String[title.length];
            RelatedSku obj = list.get(i);
            content[i][0] = obj.getRelatedListingName();
            content[i][1] = obj.getRelatedListingNameEn();
            content[i][2] = obj.getRelatedChannelName();
            content[i][3] = obj.getRelatedSku();
            content[i][4] = obj.getRelatedProductName();
            content[i][5] = obj.getRelatedProductNameEn();
            content[i][6] = obj.getProductColorName();
            content[i][7] = obj.getProductPropertyName();
            content[i][8] = obj.getProductSizeName();
            content[i][9] = obj.getRelatedFnSku();
            content[i][10] = obj.getRelatedAsin();
            content[i][11] = obj.getRelatedOperateName();
            content[i][12] = obj.getRelatedFile();
        }
        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }



}
